layui.define(['jquery', 'context', 'popup'], function (exports) {
  'use strict'

  var MOD_NAME = 'permission',
    $ = layui.jquery,
    popup = layui.popup,
    context = layui.context


  let basePath = context.get("base-path");

  var permission = new (function () { })()

  var curWwwPath = window.document.location.href
  var pathName = window.document.location.pathname
  var pos = curWwwPath.indexOf(pathName)
  var localhostPath = curWwwPath.substring(0, pos)
  var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);

  if (context.get('token') == null || context.get('token') == undefined) {
    popup.failure('暂未认证，请前往登录', function () {
      top.location.href = localhostPath + '/login.html'
    })
  }

  $.ajaxSetup({
    cache: false,
    dataType: 'json',
    contentType: 'application/json',
    type: 'post',
    headers: {
      Authorization: context.get('token')
    },
    complete: function (xhr, status) {
      if (status == "success") {
        if (xhr.status == 403) {
          popup.failure('暂无接口访问权限')
        } else if (xhr.responseJSON.statusCode == 401) {
          popup.failure('暂未认证，请前往登录', function () {
            top.location.href = localhostPath + '/login.html';
          })
        }
      }
    },
    error: function (xhr, status, error) {
      if (xhr.status == 404) {
        popup.failure('当前接口不存在');
      } else if (xhr.status == 401) {
        popup.failure('暂未认证，请前往登录', function () {
          top.location.href = localhostPath + '/login.html';
        })
      }
    }
  })

  //若当前是内嵌页面
  var frameid = $(window.frameElement).attr("data-frameid");
  if (frameid) {
    $.ajax({
      url: basePath + "/api/system/authorize/getmenubtnlist",
      data: JSON.stringify({ content: frameid }),
      success: function (result) {
        if (result.data) {//遍历，手动显示页面上的按钮
          $.each(result.data, function (index, item) {
            $("[data-unique='" + item + "']").show();
          })
        }
      }
    })
  }

  exports(MOD_NAME, permission)
})
